<template>
    <div class="user-management">
        <el-card>
            <div class="header">
                <el-input v-model="query.username" placeholder="用户名" class="search-input" />
                <el-select v-model="query.role" placeholder="权限级别" class="search-input">
                    <el-option label="Admin" :value="0"></el-option>
                    <el-option label="User" :value="1"></el-option>
                </el-select>
                <el-select v-model="query.disable" placeholder="是否被禁用" class="search-input">
                    <el-option label="Yes" :value="1"></el-option>
                    <el-option label="No" :value="0"></el-option>
                </el-select>
                <el-button type="primary" @click="fetchData">查询</el-button>
                <el-button type="primary" @click="showAddDialog">新增学生</el-button>
            </div>
        </el-card>

        <el-table :data="userList" style="width: 100%; margin-top: 20px;" v-loading="loading">
            <el-table-column prop="userId" label="ID" width="50"></el-table-column>
            <el-table-column prop="username" label="用户名"></el-table-column>
            <el-table-column prop="email" label="账号地址"></el-table-column>
            <el-table-column prop="sex" label="性别"></el-table-column>
            <el-table-column prop="grade" label="年级"></el-table-column>
            <el-table-column prop="imgUrl" label="头像">
                <template slot-scope="scope">
                    <img :src="scope.row.imgUrl" alt="avatar" class="avatar"/>
                </template>
            </el-table-column>
            <el-table-column prop="role" label="权限级别">
                <template slot-scope="scope">
                    <span>{{ scope.row.role === '0' ? 'Admin' : 'User' }}</span>
                </template>
            </el-table-column>
            <el-table-column prop="disable" label="是否封号">
                <template slot-scope="scope">
                    <el-tag :type="scope.row.disable === true ? 'danger' : 'success'">
                        {{ scope.row.disable === true ? 'Yes' : 'No' }}
                    </el-tag>
                </template>
            </el-table-column>
            <el-table-column prop="createdAt" label="创建时间"></el-table-column>
            <el-table-column label="操作">
                <template slot-scope="scope">
                    <el-button size="mini" @click="showEditDialog(scope.row)">编辑信息</el-button>
                    <el-button
                        size="mini"
                        :type="scope.row.disable === true ? 'success' : 'danger'"
                        @click="toggleUserDisable(scope.row)"
                    >
                        {{ scope.row.disable === true ? '启用账号' : '禁用账号' }}
                    </el-button>
                </template>
            </el-table-column>
        </el-table>

        <el-pagination
            background
            layout="prev, pager, next, jumper"
            :current-page="currentPage"
            :page-size="pageSize"
            :total="total"
            @current-change="handlePageChange"
            class="pagination"
        ></el-pagination>

        <el-dialog :title="isEdit ? '编辑用户信息' : '添加用户信息'" :visible.sync="dialogVisible">
            <el-form :model="currentUser" label-width="120px" class="user-form">
                <el-form-item label="用户名">
                    <el-input v-model="currentUser.username"></el-input>
                </el-form-item>
                <el-form-item label="账号">
                    <el-input v-model="currentUser.email"></el-input>
                </el-form-item>
                <el-form-item label="密码" v-if="!isEdit">
                    <el-input v-model="currentUser.password" type="password"></el-input>
                </el-form-item>
                <el-form-item label="性别">
                    <el-input v-model="currentUser.sex"></el-input>
                </el-form-item>
                <el-form-item label="年级">
                    <el-input v-model="currentUser.grade"></el-input>
                </el-form-item>
                <el-form-item label="权限">
                    <el-select v-model="currentUser.role" placeholder="用户类型">
                        <el-option label="管理员" :value="0"></el-option>
                        <el-option label="普通用户" :value="1"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="是否封禁">
                    <el-switch v-model="currentUser.disable"></el-switch>
                </el-form-item>
                <el-form-item label="头像">
                    <el-upload
                        class="avatar-uploader"
                        action="/api/upload"
                        :show-file-list="false"
                        :on-success="handleImageUploadSuccess"
                        :before-upload="beforeImageUpload"
                        :http-request="uploadRequest"
                    >
                        <el-button size="small" type="primary">上传图片</el-button>
                    </el-upload>
                    <img v-if="currentUser.imgUrl" :src="currentUser.imgUrl" class="avatar" />
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="dialogVisible = false">取消</el-button>
                <el-button type="primary" @click="isEdit ? updateUser() : createUser()">确定</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
import { fetchUserList, createUser, updateUser } from '@/api/user'
import axios from 'axios'
import Cookies from 'js-cookie'

export default {
    data() {
        return {
            query: {
                username: '',
                role: '',
                disable: ''
            },
            userList: [],
            dialogVisible: false,
            isEdit: false,
            currentUser: {
                userId: '',
                username: '',
                password: '',
                email: '',
                imgUrl: '',
                role: '',
                disable: 0
            },
            currentPage: 1,
            pageSize: 10,
            total: 0,
            loading: false
        }
    },
    methods: {
        fetchData() {
            this.loading = true
            fetchUserList({
                ...this.query,
                page: this.currentPage,
                size: this.pageSize
            }).then(response => {
                const { records, total } = response.data
                this.userList = records
                this.total = total
                this.loading = false
            }).catch(() => {
                this.loading = false
            })
        },
        showAddDialog() {
            this.isEdit = false
            this.resetCurrentUser()
            this.dialogVisible = true
        },
        showEditDialog(user) {
            this.isEdit = true
            this.currentUser = { ...user }
            this.dialogVisible = true
        },
        createUser() {
            createUser(this.currentUser).then(() => {
                this.dialogVisible = false
                this.fetchData()
            })
        },
        updateUser() {
            updateUser(this.currentUser).then(() => {
                this.dialogVisible = false
                this.fetchData()
            })
        },
        toggleUserDisable(user) {
            user.disable = user.disable === true ? false : true
            updateUser(user).then(() => {
                this.fetchData()
            })
        },
        resetCurrentUser() {
            this.currentUser = {
                userId: '',
                username: '',
                password: '',
                email: '',
                imgUrl: '',
                role: '',
                disable: 0
            }
        },
        beforeImageUpload(file) {
            const isImage = file.type.startsWith('image/')
            if (!isImage) {
                this.$message.error('Only image files are allowed!')
            }
            return isImage
        },
        handleImageUploadSuccess(response) {
            this.currentUser.imgUrl = 'http://localhost:8081/api/upload/' + response.fileName
        },
        uploadRequest({ file, onSuccess, onError }) {
            const formData = new FormData()
            formData.append('file', file)

            axios.post('/api/upload', formData, {
                headers: {
                    'Content-Type': 'multipart/form-data',
                    'X-Token': Cookies.getJSON('satoken')
                }
            })
            .then(response => {
                onSuccess(response.data)
            })
            .catch(error => {
                onError(error)
            })
        },
        handlePageChange(page) {
            this.currentPage = page
            this.fetchData()
        }
    },
    mounted() {
        this.fetchData()
    }
}
</script>

<style scoped>
.user-management {
    padding: 20px;
}
.header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
}
.search-input {
    width: 200px;
    margin-right: 10px;
}
.avatar-uploader {
    display: flex;
    align-items: center;
    margin-top: 10px;
}
.avatar {
    width: 50px;
    height: 50px;
    border-radius: 50%;
    margin-left: 20px;
}
.dialog-footer {
    text-align: right;
}
.pagination {
    margin-top: 20px;
    text-align: center;
}
</style>
